<template>
  <view class="container">
    <text class="title">方向键导航 (2x2 Grid)</text>

    <!-- 2x2 网格 -->
    <view class="grid">
      <!-- 按钮 1: 左上 -->
      <view class="btn" :class="{ active: currentPosition.row === 0 && currentPosition.col === 0 }">
        左上
      </view>

      <!-- 按钮 2: 右上 -->
      <view class="btn" :class="{ active: currentPosition.row === 0 && currentPosition.col === 1 }">
        右上
      </view>

      <!-- 按钮 3: 左下 -->
      <view class="btn" :class="{ active: currentPosition.row === 1 && currentPosition.col === 0 }">
        左下
      </view>

      <!-- 按钮 4: 右下 -->
      <view class="btn" :class="{ active: currentPosition.row === 1 && currentPosition.col === 1 }">
        右下
      </view>
    </view>

    <view class="log">
      <text>当前焦点: ({{currentPosition.row}}, {{currentPosition.col}})</text>
    </view>
  </view>
</template>

<script setup>
  import {
    ref,
    onMounted,
    onUnmounted
  } from 'vue';

  // 当前焦点的逻辑位置
  const currentPosition = ref({
    row: 0,
    col: 0
  }); // 初始在左上角

  // 长按阈值
  const LONG_PRESS_THRESHOLD = 200;

  // 按键信息存储
  const keyPressInfo = ref({});

  // 方向常量
  const UP = 'up',
    DOWN = 'down',
    LEFT = 'left',
    RIGHT = 'right';

  // 移动焦点到目标位置
  // 只有当目标位置有效时才移动
  const moveTo = (targetRow, targetCol) => {
    if (targetRow >= 0 && targetRow <= 1 && targetCol >= 0 && targetCol <= 1) {
      const oldPos = {
        ...currentPosition.value
      };
      currentPosition.value = {
        row: targetRow,
        col: targetCol
      };
      console.log(`焦点从 (${oldPos.row},${oldPos.col}) 移动到 (${targetRow},${targetCol})`);
    }
  };

  // 根据方向移动
  const moveInDirection = (direction) => {
    const {
      row,
      col
    } = currentPosition.value;
    let newRow = row,
      newCol = col;

    switch (direction) {
      case UP:
        newRow = row - 1; // 向上，行减 1
        break;
      case DOWN:
        newRow = row + 1; // 向下，行加 1
        break;
      case LEFT:
        newCol = col - 1; // 向左，列减 1
        break;
      case RIGHT:
        newCol = col + 1; // 向右，列加 1
        break;
    }

    moveTo(newRow, newCol);
  };

  // 按键抬起
  const handleKeyUp = (event) => {
    const keyCode = event.keyCode;
    const info = keyPressInfo.value[keyCode];

    if (info) {
      if (info.timer) clearTimeout(info.timer);
      delete keyPressInfo.value[keyCode];

      // 如果长按未触发，则为短按 (处理垂直移动)
      if (!info.longPressTriggered) {
        if (keyCode === 19) { // KEYCODE_DPAD_UP
          moveInDirection(UP);
        } else if (keyCode === 20) { // KEYCODE_DPAD_DOWN
          moveInDirection(DOWN);
        }
      }
    }
  };

  // 按键按下
  const handleKeyDown = (event) => {
    const keyCode = event.keyCode;
    if (keyCode !== 19 && keyCode !== 20) return; // 只处理 UP/DOWN
    if (keyPressInfo.value[keyCode]) return; // 防止重复

    const startTime = Date.now();

    // 设置长按定时器
    const timer = setTimeout(() => {
      // 长按逻辑: UP -> LEFT, DOWN -> RIGHT
      if (keyCode === 19) {
        moveInDirection(LEFT);
      } else if (keyCode === 20) {
        moveInDirection(RIGHT);
      }
      if (keyPressInfo.value[keyCode]) {
        keyPressInfo.value[keyCode].longPressTriggered = true;
      }
    }, LONG_PRESS_THRESHOLD);

    keyPressInfo.value[keyCode] = {
      startTime,
      timer,
      longPressTriggered: false
    };
  };

  onMounted(() => {
    const sys = uni.getSystemInfoSync();
    if (sys.platform === 'android') {
      plus.key.addEventListener('keydown', handleKeyDown);
      plus.key.addEventListener('keyup', handleKeyUp);
    }
  });

  onUnmounted(() => {
    const sys = uni.getSystemInfoSync();
    if (sys.platform === 'android') {
      plus.key.removeEventListener('keydown', handleKeyDown);
      plus.key.removeEventListener('keyup', handleKeyUp);
      Object.values(keyPressInfo.value).forEach(info => {
        if (info.timer) clearTimeout(info.timer);
      });
    }
  });
</script>

<style>
  .container {
    flex: 1;
    padding: 20px;
    background: #f8f9fa;
    align-items: center;
  }

  .title {
    font-size: 20px;
    font-weight: bold;
    color: #333;
    margin-bottom: 10px;
  }

  .instruction {
    font-size: 14px;
    color: #666;
    margin-bottom: 20px;
    text-align: center;
  }

  /* 2x2 网格 */
  .grid {
    display: flex;
    flex-wrap: wrap;
    width: 280px;
    gap: 10px;
    /* 按钮间距 */
  }

  /* 按钮样式 */
  .btn {
    width: 120px;
    height: 100px;
    background: #e9ecef;
    border-radius: 12px;
    justify-content: center;
    align-items: center;
    font-size: 16px;
    color: #495057;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }

  /* 激活 (焦点) 样式 */
  .btn.active {
    background: #007bff;
    color: white;
    transform: scale(1.08);
    box-shadow: 0 4px 8px rgba(0, 123, 255, 0.3);
  }

  /* 当前焦点显示 */
  .log {
    margin-top: 20px;
    font-size: 14px;
    color: #6c757d;
  }
</style>